//
//  LeaderController.swift
//  vmes
//
//  Created by user on 2021/10/25.
//

import UIKit
import Alamofire
import ESPullToRefresh

class LeaderController:BaseController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    var colltionView : UICollectionView?
    var dataArr  = NSMutableArray()//数据源
    
    let workshopLabel=UILabel()
    
    var timer:Timer?

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        initPersonView()
        initView()
//        timer=Timer.scheduledTimer(timeInterval: 10, target: self,
//                                   selector: #selector(self.getData),
//                                   userInfo: nil, repeats: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    
    func initPersonView(){
        let topLayout=UIView()
        //        topLayout.alpha=0.2
        topLayout.backgroundColor = UIColor.colorWithHex(hexStr: "#3FB59E",alpha: 1)
        topLayout.layer.shadowColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor
        topLayout.frame=CGRect(x: 15, y: statusBarHeight-30, width: width-30, height: 150)
        topLayout.roundCorners([.topLeft,.topRight], radius: 10)
        topLayout.layer.shadowOpacity = 1
        topLayout.layer.shadowRadius = 1.5
        view.addSubview(topLayout)
        
        let nameLb=UILabel()
        nameLb.textColor = .white
        nameLb.font=nameLb.font.withSize(18)
        topLayout.addSubview(nameLb)
        let roleLb=SHLabel()
        roleLb.textInsets=UIEdgeInsets(top: 3, left: 10, bottom: 3, right: 10)
        
        topLayout.addSubview(roleLb)
        let exitBtn=UILabel()
        exitBtn.text="退出"
        topLayout.addSubview(exitBtn)
        let companyLb=UILabel()
        
        companyLb.textColor = .white
        companyLb.font=companyLb.font.withSize(15)
        topLayout.addSubview(companyLb)
        nameLb.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(22)
        }
        companyLb.snp.makeConstraints { make in
            make.top.equalTo(nameLb.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(20)
        }
        workshopLabel.textColor = .white
        workshopLabel.font=companyLb.font.withSize(15)
        topLayout.addSubview(workshopLabel)
        workshopLabel.snp.makeConstraints { make in
            make.top.equalTo(companyLb.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(20)
        }
        
        
        
        roleLb.textColor = .white
        roleLb.layer.cornerRadius=12
        roleLb.font=roleLb.font.withSize(14)
        roleLb.layer.backgroundColor = UIColor.colorWithHex(hexStr: "#ffffff", alpha: 0.2).cgColor
        roleLb.snp.makeConstraints { make in
            make.left.equalTo(nameLb.snp.right).offset(20)
            make.bottom.equalTo(nameLb.snp.bottom)
        }
        exitBtn.textColor = .white
        exitBtn.font=exitBtn.font.withSize(15)
        exitBtn.alpha=0.5
        exitBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-25)
        }
        exitBtn.isUserInteractionEnabled=true
        exitBtn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showDia)))
        
        workshopLabel.isUserInteractionEnabled=true
        workshopLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showChooseDia)))
        
        //设置数据
        let userInfo = K.userInfo
        nameLb.text=userInfo?.nickName
        roleLb.text=userInfo?.post?.postName
        companyLb.text=userInfo?.company?.companyName
        K.currentWorkShop=userInfo?.workshops?.first
        setWorkShopName(name:K.currentWorkShop?.workshopName ?? "")
        
    }
    
    func setWorkShopName(name:String){
        // 图文混排
        let attrStr2 = NSAttributedString(string: name, attributes: [.foregroundColor : UIColor.white])
        let attacment2 = NSTextAttachment()
        attacment2.image = UIImage(named: "icon_switch")
        // 获取文字字体
        let font2 = workshopLabel.font
        attacment2.bounds = CGRect(x: 0, y: -4, width: (font2?.lineHeight)!, height: (font2?.lineHeight)!)
        let attrImageStr2 = NSAttributedString(attachment: attacment2)
        
        let attrMStr2 = NSMutableAttributedString()
        attrMStr2.append(attrStr2)
        attrMStr2.append(attrImageStr2)
        workshopLabel.attributedText = attrMStr2
    }
    
    @objc func showChooseDia(){
        var alert: UIAlertController!
        alert = UIAlertController(title: "", message: "请选择车间", preferredStyle: .actionSheet)
        let cleanAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        if K.userInfo?.workshops != nil{
            let dataArr = NSMutableArray()//数据源
            dataArr.addObjects(from: (K.userInfo?.workshops)!)
            for i in dataArr {
                let ii = i as! Workshop
                let action = UIAlertAction(title: ii.workshopName, style: .default, handler: {action in self.changeWorkshop(workshop:ii)})
                alert.addAction(action)
            }
        }
        
        alert.addAction(cleanAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    func changeWorkshop(workshop:Workshop){
        K.currentWorkShop=workshop
        setWorkShopName(name: workshop.workshopName ?? "")
        getData()
    }
    
    @objc func showDia(){
        self.showAlert()
    }
    
    func initView(){
        let height=Int(height) - 110 - statusBarHeight
        let layout = UICollectionViewFlowLayout()
        colltionView = UICollectionView(frame: CGRect(x: 0, y: 110+statusBarHeight, width: width, height: height), collectionViewLayout: layout)
        //注册一个cell
        colltionView!.register(MachineCell.self, forCellWithReuseIdentifier:"cell")
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        //        colltionView?.backgroundColor = UIColor.whiteColor()
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: (width-60)/3, height: 50)
        layout.sectionInset = UIEdgeInsets.init(top: 20, left: 10, bottom: 0, right: 10)
        self.view.addSubview(colltionView!)
        getData()
        
        colltionView!.es.addPullToRefresh {
            [unowned self] in
            getData()
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        if timer != nil {
                    timer?.invalidate();
                    timer = nil;
                }
    }
    //返回多少个组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
        let orderVc = OrderListController()
        orderVc.equidId=(dataArr[indexPath.item] as! MachineItem).id
        orderVc.machineInfo=dataArr[indexPath.item] as! MachineItem
        navigationController?.pushViewController(orderVc, animated: true)
        //        self.present(orderVc, animated: true, completion: nil)
    }
    
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    //返回自定义的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! MachineCell
        cell.roundCorners([.topRight], radius: 15)
        let item = dataArr[indexPath.row] as! MachineItem
        cell.titleLabel?.text = item.equipCode
        cell.titleLabel?.font = .systemFont(ofSize: 15)
        //设置颜色
        if ("G"==item.statusValue) { //生产
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#67C23A")
        } else if ("Y"==item.statusValue) { //待机
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#E6A23C")
        } else if ("R"==item.statusValue) {//故障
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#E63C3C")
        } else {// 关机
            cell.backgroundColor = UIColor.colorWithHex(hexStr: "#999999")
        }
        return cell
    }
    
    @objc func getData(){
        spinner.startAnimating()
        let comyId:String=K.userInfo?.company?.companyId ?? ""
        let parameters: Dictionary = [
            "pageNum" : "1",
            "pageSize":"99",
            "compId":comyId,
            "workshopId": K.currentWorkShop?.workshopId ?? "",
            "workshopType":K.currentWorkShop?.workshopType ?? ""
        ]
        
        sessionManager.request(NetInfo.equipList, method:.post
                               , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!).responseJSON { response in
            self.spinner.stopAnimating()
            self.colltionView!.es.stopPullToRefresh()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(MachineList.self, from: data)
                    if(response?.code==200){
                        self.dataArr.removeAllObjects()
                        self.dataArr.addObjects(from: (response?.rows)!)
                        self.colltionView?.reloadData()
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
}
